package com.nervenets.shopping.service.impl;

import com.nervenets.general.redis.RedisSyncLocker;
import com.nervenets.general.service.impl.BaseServiceImpl;
import com.nervenets.general.utils.JodaUtils;
import com.nervenets.shopping.hibernate.dao.DataOfUserDao;
import com.nervenets.shopping.hibernate.domain.data.DataOfUser;
import com.nervenets.shopping.service.DataOfUserService;
import com.nervenets.shopping.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class DataOfUserServiceImpl extends BaseServiceImpl<DataOfUser, DataOfUserDao> implements DataOfUserService {
    @Resource
    private RedisSyncLocker<Void> redisSyncLocker;
    @Resource
    private UserService userService;

    @Override
    public DataOfUser checkAndGenerateData(long timestamp) {
        DataOfUser dataOfUser = dao.findByCreateTime(timestamp);
        if (null == dataOfUser) {
            dataOfUser = new DataOfUser();
            dataOfUser.setCreateTime(timestamp);
            save(dataOfUser);
        }
        return dataOfUser;
    }

    @Override
    public void updateData(long newer, long pay, long active, long refund) throws Exception {
        final long startOfToday = JodaUtils.getStartOfToday();
        redisSyncLocker.keyLock("DataOfUser" + startOfToday, () -> {
            DataOfUser dataOfUser = checkAndGenerateData(startOfToday);
            dataOfUser.setTotal(userService.count());
            if (newer != 0) dataOfUser.setNewer(newer);
            if (pay != 0) dataOfUser.setPay(pay);
            if (active != 0) dataOfUser.setActive(active);
            if (refund != 0) dataOfUser.setRefund(refund);
            save(dataOfUser);
            return null;
        });
    }
}
